<?php

namespace app\admin\controller;

use app\admin\model\NewsModel;
use think\Db;
use think\Exception;
use think\Request;

class News extends Base
{
    public function lists (Request $request)
    {
        $newsModel = new NewsModel();
        $list = $newsModel->getList ([], $request->get ('p'), 10);
        return view ('lists', [
            'list' => $list,
        ]);
    }

    public function detail (Request $request)
    {
        $newsModel = new NewsModel();
        if ($request->isPost ()) {
            //修改逻辑
            $id = $request->post ('id');
            $detail = [
                'title'       => $request->post ('title'),
                'author'      => $request->post ('author'),
                'url'         => $request->post ('url'),
                'description' => $request->post ('description'),
                'content'     => $request->post ('content'),
                'pic'         => $request->post ('pic'),
                'status'      => $request->post ('status'),
                'type'        => $request->post ('type'),
                'updated_at'  => time ()
            ];
            try {
                if (empty($id)) {
                    $detail['created_at'] = $detail['updated_at'];
                    $newsModel->create ($detail);
                } else {
                    $newsModel->where (['id' => $id])->update ($detail);
                }
                $this->ajaxMsg ('SUCCESS');
            } catch (Exception $e) {
                $this->ajaxMsg ($e->getMessage (), '500');
            }
        } else {
            //查看逻辑
            $id = $request->get ('id');
            $newsType = Db::table ('tps_news_type')->field ('id,type_name')->select ();
            if (empty($id)) $detail = ['id' => '', 'title' => '', 'author' => '', 'url' => '', 'description' => '', 'content' => '', 'pic' => '', 'status' => '', 'type' => ''];
            else $detail = $newsModel->getDetails (['n.id' => $id]);
            return view ('detail', [
                'detail'   => $detail,
                'newsType' => $newsType
            ]);
        }
    }
}
